package lowijs.XfDroid;

import static lowijs.XfDroid.FriendDBAdapter.KEY_CHANNEL_ID;
import static lowijs.XfDroid.FriendDBAdapter.KEY_GAMEID;
import static lowijs.XfDroid.FriendDBAdapter.KEY_NICKNAME;
import static lowijs.XfDroid.FriendDBAdapter.KEY_ONLINE;
import static lowijs.XfDroid.FriendDBAdapter.KEY_ROWID;
import static lowijs.XfDroid.FriendDBAdapter.KEY_STATUSTEXT;
import static lowijs.XfDroid.FriendDBAdapter.OFFLINE_FLAG;
import static lowijs.XfDroid.XfDroidConstants.ARG_0;
import static lowijs.XfDroid.XfDroidConstants.ARG_1;
import static lowijs.XfDroid.XfDroidConstants.DC_REASON;
import static lowijs.XfDroid.XfDroidConstants.PREF_MOBILE_WARNINGS;
import static lowijs.XfDroid.XfDroidConstants.PREF_SHOW_OFFLINE;
import static lowijs.XfDroid.XfDroidConstants.PREF_THEME;
import static lowijs.XfDroid.XfDroidConstants.PREF_THEME_ANDROID;
import static lowijs.XfDroid.XfDroidConstants.PREF_THEME_DEFAULT;
import static lowijs.XfDroid.XfDroidConstants.PROFILE_URL;
import static lowijs.XfDroid.XfDroidConstants.STATE_AFK;
import static lowijs.XfDroid.XfDroidConstants.STATE_NICKNAME;
import static lowijs.XfDroid.XfDroidConstants.STATE_SET_NICKNAME;
import static lowijs.XfDroid.XfDroidConstants.STATE_SET_STATUS;
import static lowijs.XfDroid.XfDroidConstants.STATE_STATUS_TEXT;

import java.sql.SQLException;
import java.util.Map;
import java.util.TreeMap;

import lowijs.XfireClient.XfireObserver;
import lowijs.XfireClient.event.EventManager;
import lowijs.XfireClient.event.ToastEvent;
import lowijs.XfireClient.event.XfireEvent;
import lowijs.XfireClient.packet.Packet;
import lowijs.util.logging.Logging;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SimpleCursorAdapter.ViewBinder;

import com.googlecode.xfdroid.R;

public class Friendslist extends ListActivity implements XfireObserver {
	private static final int LOGIN_ACTION = 1;

	private static final int RECONNECT_ACTION = 2;

	private AlertDialog ad = null;

	private Cursor cursor;

	private Cursor current; 

	private int skin;

	private SimpleCursorAdapter adapter;

	private Map<Integer, Drawable> bitmaps;

	private SharedPreferences prefs;

	private Drawable empty;

	private FriendDBAdapter db;

	private boolean offline;

	private Handler toastHandler = new Handler() {
		public void handleMessage(Message m) {
			String message = (String)m.obj;
			Toast t = Toast.makeText(getBaseContext(), message, 2);
			t.show();
		}
	};

	public void onCreate(Bundle b) {
		super.onCreate(b);
		Logging.getLogging().friendsOnCreate();

		ensureLogin();
		empty = getResources().getDrawable(R.drawable.unknown);
		prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

		// Install our error handler
		ErrorHandler.install();

		db = FriendDBAdapter.getInstance(getBaseContext());
		bitmaps = new TreeMap<Integer, Drawable>();

		try {
			initCurssor();

			skin = R.layout.friendrow;

			adapter = new SimpleCursorAdapter(this, skin, cursor, new String[] {KEY_ONLINE, KEY_NICKNAME, KEY_STATUSTEXT, KEY_GAMEID}, new int[] {R.id.tvBanner, R.id.tvNickname, R.id.tvStatusText, R.id.ivImage});
			adapter.setViewBinder(new ViewBinder() {
				public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
					if (view.getId() == R.id.ivImage) {
						ImageView iv = (ImageView)view;
						int gid = cursor.getInt(columnIndex);
						Drawable btmp = empty;

						if (gid > 0) {
							Integer key = Integer.valueOf(gid);
							btmp = bitmaps.get(key);

							if (btmp == null) {
								String path = Packet.getGamedataById(gid);

								if (path == null) {
									btmp = empty;
								} else {
									btmp = BitmapDrawable.createFromPath(path);
								}

								bitmaps.put(key, btmp);
							}
						}

						iv.setImageDrawable(btmp);

						return true;
					} else if (skin != R.layout.friendrow && view.getId() == R.id.tvBanner) {
						TextView tv = (TextView)view;
						int online = cursor.getInt(columnIndex);
						boolean show = false;

						if (cursor.getPosition() == 0) {
							show = true;
						} else {
							cursor.moveToPrevious();
							int previous = cursor.getInt(columnIndex);
							cursor.moveToNext();
							show = online != previous;
						}

						if (show) {
							tv.setVisibility(View.VISIBLE);
							tv.setText(getString(online == OFFLINE_FLAG ? R.string.friends_offline_contacts : R.string.friends_online_contacts));
						} else {
							tv.setVisibility(View.GONE);
						}

						return true;
					}

					return false;
				}
			});
			setListAdapter(adapter);

			current = db.current();
			startManagingCursor(current);
			current.registerContentObserver(new ContentObserver(new MHandler()) {
			});
		} catch (Exception e) {
			Logging.getLogging().clientException("Problem creating queries", e);
		}

		ListView lv = getListView();
		View.OnCreateContextMenuListener listener =
			new View.OnCreateContextMenuListener() {
				public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
					int position = ((AdapterContextMenuInfo)menuInfo).position;
					cursor.moveToPosition(position);
					long userid = cursor.getLong(0);
					String nick = cursor.getString(2);
					FriendDBAdapter db = FriendDBAdapter.getInstance(getBaseContext());
					Map<Integer, Integer> notifications = db.getNotifications(userid);

					getMenuInflater().inflate(R.menu.menu_friendslist_context, menu);

					((MenuItem)menu.findItem(R.id.menu_friendslist_context_notifyonline)).setChecked(getBoolean(notifications.get(2)));
					((MenuItem)menu.findItem(R.id.menu_friendslist_context_notifyoffline)).setChecked(getBoolean(notifications.get(1)));

					menu.setHeaderTitle(nick);
				}

				private boolean getBoolean(Integer integer) {
					return integer == null ? false : integer.intValue() != 0;
				}
			};
		lv.setOnCreateContextMenuListener(listener);
	}

	private void initCurssor() {
		if (cursor != null) {
			stopManagingCursor(cursor);
		}

		offline = prefs.getBoolean("XfDroid.showOffline", true);

		if (offline) {
			cursor = db.getAllFriends();
		} else {
			cursor = db.getOnlineFriends();
		}

		startManagingCursor(cursor);

		if (adapter != null) {
			adapter.changeCursor(cursor);
		}
	}

	public void setSkin(int skin) {
		if (this.skin != skin) {
			this.skin = skin;
			adapter.setViewResource(skin);
		}
	}

	public void onDestroy() {
		Logging.getLogging().friendsOnDestroy();
		super.onDestroy();

		stopManagingCursor(cursor);
		cursor.close();
		current.close();
		current = null;
		cursor = null;
	}

	class MHandler extends Handler {
		@Override
		public void dispatchMessage(Message msg) {
			if (current != null) {
				try {
					current.requery();
				} catch (Exception e) {
					Log.e(XfDroidConstants.LOG_TAG, e.getMessage(), e);
				}
			}

			setupTitle();
		}
	}

	private void setupTitle() {
		if (!XfDroidService.isConnected()) {
			setTitle(getString(R.string.friends_offline_title));
		} else if (current != null) {
			String who = null;
			String sts = null;

			if (current.moveToFirst()) {
				who = current.getString(current.getColumnIndex(KEY_NICKNAME));
				sts = current.getString(current.getColumnIndex(KEY_STATUSTEXT));
			} else {
				who = getString(R.string.no_nickname);
				sts = getString(R.string.status_offline);
			}

			String title = getString(R.string.friends_online_title);
			title = title.replace(ARG_0, who);
			title = title.replace(ARG_1, sts);
			setTitle(title);
		} else {
			String title = getString(R.string.friends_online_title);
			title = title.replace(ARG_0, "Error");
			title = title.replace(ARG_1, "Error");
			setTitle(title);
		}
	}
	
	public void onStart() {
		Logging.getLogging().friendsOnStart();
		ensureLogin();
		EventManager.addObserver(this);
		XfDroidService.sendAllNotifications();
		super.onStart();

		if (prefs.getString(PREF_THEME, PREF_THEME_DEFAULT).equals(PREF_THEME_ANDROID)) {
			setSkin(R.layout.android_friendrow);
		} else {
			setSkin(R.layout.friendrow);
		}

		boolean noff = prefs.getBoolean(PREF_SHOW_OFFLINE, true);

		if (offline != noff) {
			initCurssor();
		}

		setupTitle();
	}

	public void ensureLogin() {
		if (XfDroidService.isReconnecting()) {
			showReconnect();
		} else if (!XfDroidService.isConnected()) {
			showLogin(false);
		}
	}

	public void onStop() {
		Logging.getLogging().friendsOnStop();
		EventManager.removeObserver(this);

		if (ad != null) {
			ad.dismiss();
		}

		super.onStop();
	}

	public void onSaveInstanceState(Bundle b) {
		Logging.getLogging().friendsOnSaveInstanceState();
		if (ad != null && ad.isShowing()) {
			EditText etNickname = (EditText)ad.findViewById(R.id.etNickname);

			if (etNickname != null) {
				b.putBoolean(STATE_SET_NICKNAME, true);
				b.putString(STATE_NICKNAME, etNickname.getText().toString());
			}

			CheckBox cbAfk = (CheckBox)ad.findViewById(R.id.cbAfk);
			EditText etStatusText = (EditText)ad.findViewById(R.id.etStatusText);

			if (cbAfk != null && etStatusText != null) {
				b.putBoolean(STATE_SET_STATUS, true);
				b.putBoolean(STATE_AFK, cbAfk.isChecked());
				b.putString(STATE_STATUS_TEXT, etStatusText.getText().toString());
			}
		}
		super.onSaveInstanceState(b);
	}
	
	public void onRestoreInstanceState(Bundle b) {
		Logging.getLogging().friendsOnRestoreInstanceState();
		if (b.getBoolean(STATE_SET_NICKNAME)) {
			showSetNickDialog(b.getString(STATE_NICKNAME));
			b.remove(STATE_NICKNAME);
			b.remove(STATE_SET_NICKNAME);
		}

		if (b.getBoolean(STATE_SET_STATUS)) {
			showSetStatusDialog(b.getString(STATE_STATUS_TEXT), b.getBoolean(STATE_AFK));
			b.remove(STATE_STATUS_TEXT);
			b.remove(STATE_AFK);
			b.remove(STATE_SET_STATUS);
		}

		super.onRestoreInstanceState(b);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		Logging.getLogging().friendsOnCreateOptionsMenu();
		getMenuInflater().inflate(R.menu.menu_friendslist, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		Logging.getLogging().friendsOnOptionsItemSelected();
		switch(item.getItemId()) {
		case R.id.menu_friendslist_logoff:
			Logging.getLogging().loggingOff();
			XfDroidService.logoff();
			return true;
		case R.id.menu_friendslist_setnick:
			if (current.moveToFirst()) {
				String nick =current.getString(current.getColumnIndex(KEY_NICKNAME));
				showSetNickDialog(nick);
			}

			return true;
		case R.id.menu_friendslist_setstatus:
			String status = XfDroidService.getStatusText();

			if (status == null) {
				status = getString(R.string.status_offline);
			}

			showSetStatusDialog(status, false);
			return true;
		case R.id.menu_friendslist_profile:
			showProfile(FriendDBAdapter.getInstance(getBaseContext()).getMyid());
			return true;
		case R.id.menu_friendslist_preferences:
			startActivity(new Intent(this, XfDroidPrefs.class));
			return true;
		}
		return false;
	}
	
	private void showLogin(boolean dcReason) {
		Logging.getLogging().friendsShowLogin();
		Intent login = new Intent(this, Login.class);

		if (dcReason) {
			login.putExtra(DC_REASON, true);
		}

		startActivityForResult(login, LOGIN_ACTION);
		finish();
	}
	
	private void showReconnect() {
		Logging.getLogging().friendsShowReconnect();
		// Will try to reconnect, show reconnect activity
		Intent reconnect = new Intent(this, ReconnectActivity.class);
		startActivityForResult(reconnect, RECONNECT_ACTION);
		finish();
	}

	public boolean onContextItemSelected(MenuItem item) {
		Logging.getLogging().friendsOnContextItemSelected();
		AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		long id = menuInfo.id;

		switch(item.getItemId()) {
		case R.id.menu_friendslist_context_viewprofile:
			showProfile(id);
			return true;
		case R.id.menu_friendslist_context_viewscreens:
			ConnectivityManager cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);

			// if we're on a mobile network and the setting is on, show warning
			if (prefs.getBoolean(PREF_MOBILE_WARNINGS, true) && cm.getActiveNetworkInfo().getType() == 0) {
				ad = new AlertDialog.Builder(this)
					.setTitle(R.string.warning)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setMessage(R.string.on_mobile_expl)
					.setPositiveButton(R.string.yes, new MyOnClickListener(id))
					.setNegativeButton(R.string.no, null)
					.create();

				ad.show();
			} else {
				showScreenshotsFor(id);
			}

			return true;
		case R.id.menu_friendslist_context_notifyoffline:
			toggleType(id, 1);
			return true;
		case R.id.menu_friendslist_context_notifyonline:
			toggleType(id, 2);
			return true;
		}

		return false;
	}

	private void toggleType(long userid, int type) {
		FriendDBAdapter db = FriendDBAdapter.getInstance(getBaseContext());
		db.toggleWatch(userid, type);
	}

	class MyOnClickListener implements DialogInterface.OnClickListener {
		private long rowid;

		public MyOnClickListener(long rowid) {
			this.rowid = rowid;
		}

		public void onClick(DialogInterface dialog, int which) {
			showScreenshotsFor(rowid);					
		}
	}

	private void showProfile(long id) {
		FriendDBAdapter db = FriendDBAdapter.getInstance(getBaseContext());
		String name = db.username(id);
		showBrowserFor(PROFILE_URL + name);
	}

	private void showScreenshotsFor(long rowid) {
		Intent i = new Intent(this, Screenshots.class);
		i.putExtra(KEY_ROWID, rowid);
		startActivity(i);
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id) {
		try {
			long channelid = FriendDBAdapter.getInstance(getApplicationContext()).openChannel(id);

			if (channelid > 0) {
				Intent i = new Intent(this, ConvoWindow.class);
				i.putExtra(KEY_CHANNEL_ID, channelid);
				startActivity(i);
			} else {
				Toast.makeText(this, getString(R.string.friends_no_history), Toast.LENGTH_SHORT).show();
			}
		
			super.onListItemClick(l, v, position, id);
		} catch (SQLException e) {
			e.printStackTrace();
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}
		
	private void showBrowserFor(String url) {
		Uri uri = Uri.parse(url);
		Intent i = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(i);
	}
	
	private void showSetStatusDialog(String statustext, boolean checked) {
		DialogInterface.OnClickListener listener =
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CheckBox cb = (CheckBox)ad.findViewById(R.id.cbAfk);
					if(cb.isChecked()) {
						XfDroidService.setStatusText(getString(R.string.status_afk));
					} else {
						EditText et = (EditText)ad.findViewById(R.id.etStatusText);
						XfDroidService.setStatusText(et.getText().toString());
					}
					setupTitle();
				}
			};
		
		DialogInterface.OnClickListener clearListener =
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					XfDroidService.setStatusText(getString(R.string.status_online));
					setupTitle();
				}
			};
		
		View v = getLayoutInflater().inflate(R.layout.setstatus_dialog, null);
		
		ad = new AlertDialog.Builder(this)
		.setView(v)
		.setPositiveButton(R.string.ok, listener)
		.setNeutralButton(R.string.reset_status, clearListener)
		.setTitle(R.string.set_status)
		.create();
		ad.show();

		OnCheckedChangeListener checkedListener =
			new OnCheckedChangeListener() {
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					EditText etStatusText =
						(EditText)ad.findViewById(R.id.etStatusText);
					etStatusText.setEnabled(!isChecked);
				}
			};
		
		CheckBox cb = (CheckBox)ad.findViewById(R.id.cbAfk);
		cb.setOnCheckedChangeListener(checkedListener);
		cb.setChecked(checked);
		
		EditText et = (EditText)ad.findViewById(R.id.etStatusText);
		et.setText(statustext);
	}
	
	private void showSetNickDialog(String nick) {
		DialogInterface.OnClickListener listener =
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
                    EditText etNickname = (EditText)ad.findViewById(R.id.etNickname);
                    XfDroidService.setNickname(etNickname.getText().toString());
				}
			};
			
		View v = getLayoutInflater().inflate(R.layout.setnick_dialog, null);
		
		ad = new AlertDialog.Builder(this)
		.setView(v)
		.setPositiveButton(R.string.ok, listener)
		.setTitle(R.string.new_nickname)
		.create();
		
		ad.show();
		((EditText)ad.findViewById(R.id.etNickname)).setText(nick);
	}

	public void handleEvent(XfireEvent event) {
		boolean dcReason = false;

		switch(event.getEventType()) {
		case XfireEvent.XF_DCREASON:
			dcReason = true;
		case XfireEvent.XF_OFFLINE:
			showLogin(dcReason);
			return;
		case XfireEvent.XF_LOST_CONNECTION:
			Logging.getLogging().lostConnection();
			showReconnect();
			return;
		case XfireEvent.XF_TOAST:
			ToastEvent toast = (ToastEvent)event;
			Message message = new Message();
			message.obj = toast.getMessage();
			toastHandler.sendMessage(message);
			return;
		case XfireEvent.XF_FRSTATUS:
		case XfireEvent.XF_FRGAME:
		case XfireEvent.XF_FRSTATUSTEXT:
			//SimpleCursorAdapter sca = (SimpleCursorAdapter)getListAdapter();
			//cursor = FriendDBAdapter.INSTANCE.getAllFriends();
			//setListAdapter(new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, new String[] {FriendDBAdapter.KEY_USERNAME, FriendDBAdapter.KEY_NICKNAME}, new int[] {android.R.id.text1, android.R.id.text2}));
			//friendslistHandler.sendEmptyMessage(0);
			return;
		}
	}
}
